﻿using ETask.Api.Data;
using ETask.Api.Dtos;
using ETask.Api.Mappers;
using ETask.Api.Models;
using ETask.Api.Repositories;

namespace ETask.Api.Services
{
    public class TaskFileService : GenericService<TaskFile, TaskFileDto, CreateTaskFileDto, UpdateTaskFileDto>, ITaskFileService
    {
        private readonly ITaskFileRepository _repository;

        private string _rootPath;

        private long _fileMaxFile;

        private string _fileExts;

        public TaskFileService(ITaskFileRepository repository, GenericMapper<TaskFile, TaskFileDto, CreateTaskFileDto, UpdateTaskFileDto> mapper) : base(repository, mapper)
        {
            _repository = repository;
        }

        public async Task<ApiResponse> DelByFileId(int fileId)
        {
            TaskFileDto taskDto = await GetByIdAsync(fileId);
            if (taskDto == null)
            {
                return ApiResponse.Fail(400, "文件不存在");
            }
            string filePath = taskDto.FilePath;
            string fullPath = Path.Combine(_rootPath, filePath);
            if (!File.Exists(fullPath))
            {
                return ApiResponse.Fail(400, "文件不存在");
            }
            await _repository.DeleteAsync(fileId);
            File.Delete(fullPath);
            return ApiResponse.Ok("删除成功");
        }

        public async Task<ApiResponse> DeleteByFolderId(string folderId)
        {
            var list = await _repository.FindAllAsync(q => q.FolderId.Equals(folderId));
            foreach (var item in list)
            {
                string fullPath = Path.Combine(_rootPath, item.FilePath);
                if (!File.Exists(fullPath))
                {
                    continue;
                }
                File.Delete(fullPath);
            }
            await _repository.DeleteListAsync(list.ToArray());
            return ApiResponse.Ok("删除成功");
        }

        public async Task<List<TaskFileDto>> GetListByFolderIdAsync(string folderId)
        {
            return await _repository.GetListByFolderIdAsync(folderId);
        }

        public async Task<ApiResponse> Upload(IFormFile file,string folderId = "")
        {
            if (string.IsNullOrWhiteSpace(folderId))
            {
                folderId = Guid.NewGuid().ToString();
            }
            try
            {
                // 验证文件是否存在
                if (file == null || file.Length == 0)
                {
                    return ApiResponse.Fail(400, "请选择要上传的文件");
                }

                if (file.Length > _fileMaxFile)
                {
                    return ApiResponse.Fail(400, $"文件大小不能超过{_fileMaxFile / 1024 / 1024}MB");
                }

                string[] allowedExtensions = _fileExts.Split(',', StringSplitOptions.TrimEntries);
                var fileExtension = Path.GetExtension(file.FileName).ToLower();
                if (!Array.Exists(allowedExtensions, ext => ext == fileExtension))
                {
                    return ApiResponse.Fail(400, $"只允许上传{_fileExts}格式的文件");
                }
                var currentDate = DateTime.Now;
                var dateFolder = Path.Combine(
                    currentDate.Year.ToString(),
                    currentDate.Month.ToString("D2"),
                    currentDate.Day.ToString("D2")
                );
                var fileName = $"{Guid.NewGuid()}{fileExtension}";
                var savePath = Path.Combine(_rootPath, dateFolder);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                var fullFilePath = Path.Combine(savePath, fileName);
                using (var stream = new FileStream(fullFilePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                LoginUser loginUser = UserContext.CurrentUser;
                TaskFile taskFile = new TaskFile();
                taskFile.FileName = fileName;
                taskFile.FileExtension = fileExtension;
                taskFile.OriginFileName = file.FileName;
                taskFile.CreateBy = loginUser.Id;
                taskFile.FileSize = file.Length;
                taskFile.FilePath = fullFilePath;
                taskFile.FolderId = folderId;
                taskFile.CreatedAt = DateTime.Now;
                await _repository.AddAsync(taskFile);
                return ApiResponse.Ok(new {
                    folderId = folderId,
                    fileId = taskFile.Id
                });
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(400, "上传失败");
            }
        }
    }

}